package response;

import config.Config;
import request.Request;

import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

public class CGIResponse {
    public static Response response(Request request) {
        String exe = Config.getConfig().getWebRoot() + "/cgibin" + request.getResource();
        Response response = new Response();

        try {
            String result = executeExe(exe, request.getPostData());
            System.out.println("return: " + result);
            List<String> lines = result.lines().collect(Collectors.toList());
            String contentType = lines.get(0).split(":")[1].trim();
            String content = result.lines().skip(1).reduce((a, b) -> a + "\n" + b).get();

            response.setContentType(contentType);
            response.setStatusCode(200);
            response.setContent(content);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(500);
            response.setContent("internal server error");
        }

        return response;
    }

    private static String executeExe(String file, String input) {
        System.out.println(file);
        System.out.println(input);

        input += "\n";

        Runtime runtime = Runtime.getRuntime();

        try {
            String cmd = file.replaceAll("/", "\\\\");
            Process process = runtime.exec(cmd);

            OutputStream outputStream = process.getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()
            ));

            int r = process.waitFor();
            System.out.println("return value: " + r);

            StringBuilder sb = new StringBuilder();
            String temp = bufferedReader.readLine();
            while (temp != null) {
                sb.append(temp).append("\n");
                temp = bufferedReader.readLine();
            }

            return new String(sb);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "666";
    }
}
